﻿using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using SmartCity.Shared;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace MetroManagement
{
    /// <summary>
    /// 乘车记录应用服务类
    /// </summary>
    public class RecordAppService : ApplicationService, IRecordAppService
    {
        private readonly IAuthManager _authManager;
        private readonly IRepository<Record, int> _recordRepository;

        public RecordAppService(
            IAuthManager authManager,
            IRepository<Record, int> recordRepository)
        {
            _authManager = authManager;
            _recordRepository = recordRepository;
        }

        // 分页列表
        public async Task<ListResponse<RecordDto>> PagedListAsync(PagedListRequest request)
        {
            // 过滤
            var userId = _authManager.GetUserId();
            var query = _recordRepository
                .Where(m => m.UserId == userId);
            // 计数
            var count = query.Count();
            // 排序
            if (!string.IsNullOrWhiteSpace(request.OrderByColumn))
            {
                var orderColumns = request.OrderByColumn.Split(',');
                foreach (var column in orderColumns)
                {
                    query = query.OrderBy(column);
                }
            }
            // 分页
            query = query.Page(request.PageNum, request.PageSize);
            // 返回结果
            var list = await query.ToListAsync();
            var dtos = ObjectMapper.Map<List<Record>, List<RecordDto>>(list);
            return ListResponse<RecordDto>.Successful(count, dtos);
        }
    }
}